package cn.fintecher.pangolin.service.manage.service;

import cn.fintecher.pangolin.common.enums.BaseSelect;
import cn.fintecher.pangolin.common.enums.StatusType;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.UserModel;
import cn.fintecher.pangolin.common.utils.BeanUtils;
import cn.fintecher.pangolin.entity.mysql.QStatusConfig;
import cn.fintecher.pangolin.entity.mysql.StatusConfig;
import cn.fintecher.pangolin.service.manage.repository.StatusConfigRepository;
import cn.fintecher.pangolin.service.manage.request.AddConfigRequest;
import cn.fintecher.pangolin.service.manage.request.ModifyConfigRequest;
import cn.fintecher.pangolin.service.manage.response.StatusConfigResponse;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.collections4.IterableUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 9:54 2019/9/7
 */

@Service("statusConfigService")
@Transactional(rollbackFor = Exception.class)
public class StatusConfigService {
    @Autowired
    private StatusConfigRepository statusConfigRepository;

    @Autowired
    private BaseService baseService;

    /**
     * 新增配置
     */
    public void addConfig(AddConfigRequest request) {
        StatusConfig statusConfig = new StatusConfig();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        QStatusConfig qStatusConfig = QStatusConfig.statusConfig;
        booleanBuilder.and(qStatusConfig.principalId.eq(request.getPrincipalId()))
                .and(qStatusConfig.name.eq(request.getName()).or(qStatusConfig.code.eq(request.getCode())));
        boolean exists = statusConfigRepository.exists(booleanBuilder);
        if (exists) {
            throw new BadRequestException(null, "", "config.is.exists");
        }
        BeanUtils.copyPropertiesIgnoreNull(request, statusConfig);
        statusConfigRepository.save(statusConfig);
    }

    /**
     * 修改配置
     */
    public void modifyConfig(ModifyConfigRequest request) {
        StatusConfig statusConfig = statusConfigRepository.findById(request.getId()).orElseThrow(() -> new BadRequestException(null, "statusConfig", "config.is.null"));
        statusConfig.setCode(request.getCode());
        statusConfig.setColor(request.getColor());
        statusConfig.setName(request.getName());
        statusConfig.setSort(request.getSort());
        statusConfig.setIsImportant(request.getIsImportant());
        statusConfigRepository.save(statusConfig);
    }

    /**
     * 删除配置
     */
    public void deleteConfig(String id) {
        statusConfigRepository.deleteById(id);
    }

    /**
     * 查询全部配置
     */
    public Page<StatusConfig> findAllConfig(StatusType type, String principalId, Pageable pageable, String token) {
        UserModel userModel = baseService.getUserByToken(token);
        BooleanBuilder builder = new BooleanBuilder();
        if (userModel.getIsCheck().equals(BaseSelect.YES)) {
            builder.and(QStatusConfig.statusConfig.principalId.in(userModel.getPrincipalIds()));
        }
        if (Objects.nonNull(type)) {
            builder.and(QStatusConfig.statusConfig.type.eq(type));
        }
        if (Objects.nonNull(principalId)) {
            builder.and(QStatusConfig.statusConfig.principalId.eq(principalId));
        }
        builder.and(QStatusConfig.statusConfig.principalId.isNotNull());
        return statusConfigRepository.findAll(builder, pageable);
    }

    /**
     * 不分页查询全部配置
     */
    public List<StatusConfig> findAllConfigNoPage(StatusType type, String token) {
        UserModel userModel = baseService.getUserByToken(token);
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(QStatusConfig.statusConfig.type.eq(type));
        if (userModel.getIsCheck().equals(BaseSelect.YES)) {
            builder.and(QStatusConfig.statusConfig.principalId.in(userModel.getPrincipalIds()));
        }
        Iterable<StatusConfig> iterable = statusConfigRepository.findAll();
        return IterableUtils.toList(iterable);
    }

    /**
     * 获取手工状态
     */
    public StatusConfigResponse getStatusConfig(String principalId) {
        Iterable<StatusConfig> iterable = statusConfigRepository.findAll(QStatusConfig.statusConfig.type.in(StatusType.CONTACT_STATUS, StatusType.COLLECT_STATUS)
                .and(QStatusConfig.statusConfig.principalId.eq(principalId)));
        List<StatusConfig> contactStatus = new ArrayList<>();
        List<StatusConfig> collectStatus = new ArrayList<>();
        iterable.forEach(e -> {
            if (e.getType().equals(StatusType.CONTACT_STATUS)) {
                contactStatus.add(e);
            } else {
                collectStatus.add(e);
            }
        });
//        contactStatus.sort(Comparator.comparing(StatusConfig::getSort));
//        collectStatus.sort(Comparator.comparing(StatusConfig::getSort));
        StatusConfigResponse response = new StatusConfigResponse();
        response.setContactStatus(contactStatus);
        response.setCollectStatus(collectStatus);
        return response;
    }
}
